/**
 * 	 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *   @author Colin Redmond
 *   Copyright (C) 2011 Colin Redmond
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.cred.industries.platform.dao;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.List;


import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

import com.cred.industries.platform.bo.CustomerTestBO;
import com.cred.industries.platform.server.IServerResource;
import com.cred.industries.platform.trans.CustomerTestTrans;
import com.cred.industries.platform.transferObj.CustomerTransList;
import com.cred.industries.platform.transferObj.CustomerTrans;
import com.sun.jersey.api.client.WebResource;

public class CustomerTestDAO {
	
	private static final Logger logger = LoggerFactory.getLogger(CustomerTestDAO.class);
	
	public void create(CustomerTestBO createCustBO, IServerResource server) {
		
		
		WebResource resource = server.getResource();
	
		Document doc = null;
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		
		try {
			//build the request and data we send to the server
			doc = dbf.newDocumentBuilder().newDocument();
			JAXBContext jaxbContextDetailed = JAXBContext.newInstance(CustomerTestTrans.class);
			Marshaller marshaller = jaxbContextDetailed.createMarshaller();
		
			//create the xml out of the DetailedCustomerTrans
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal(createCustBO.getCreateCustTrans(), doc);

			
			StringWriter sw = new StringWriter();
			TransformerFactory tf = TransformerFactory.newInstance();
	        Transformer transformer;
			try {
				transformer = tf.newTransformer();
		        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
		        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
		        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		        transformer.transform(new DOMSource(doc), new StreamResult(sw));
			} catch (TransformerConfigurationException e1) {
				e1.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			}
	        String s = sw.toString();
			System.out.println(s);

			 
			//Call the server and get the result back  
			String response = resource.path("customer").path("create").post(String.class, doc);
			
			//unmashall the return results
			InputStream inputStream = new ByteArrayInputStream(response.getBytes());
			JAXBContext jaxbContextShort = JAXBContext.newInstance(CustomerTrans.class);
			Unmarshaller unmarshaller = jaxbContextShort.createUnmarshaller();
			CustomerTrans custTrans = (CustomerTrans) unmarshaller.unmarshal(inputStream);
			
			//update the local customer with the new customerId
			CustomerTestTrans custTransRes = createCustBO.getCreateCustTrans();
			custTransRes.customerId = custTrans.getCustomerId();
			createCustBO.setCreateCustTrans(custTransRes);
			
			//assertTrue(mCustTrans.customerId == createCustTrans.customerId);
		} catch (ParserConfigurationException e) {
			logger.error("ParserConfigurationException " + e.getMessage());
		}  catch (JAXBException e) {
			logger.error("JAXBException "  + e.getMessage());
		} 
	}
	
	public void update(CustomerTestBO updateCustBO, IServerResource server) {
		
		WebResource resource = server.getResource();
	
		Document doc = null;
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		
		try {
			//build the request and data we send to the server
			doc = dbf.newDocumentBuilder().newDocument();
			JAXBContext jaxbContextDetailed = JAXBContext.newInstance(CustomerTestTrans.class);
			Marshaller marshaller = jaxbContextDetailed.createMarshaller();
		
			//create the xml out of the DetailedCustomerTrans
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal(updateCustBO.getCreateCustTrans(), doc);

			//Call the server and get the result back
			String result = resource.path("customer")
				.header("Content-Type", javax.ws.rs.core.MediaType.APPLICATION_XML)
				.header(DAODefines.SESSIONID_HEADER, updateCustBO.getSessionId())
				.put(String.class, doc);
			
			//unmashall the return results
			InputStream inputStream = new ByteArrayInputStream(result.getBytes());
			Unmarshaller unmarshaller = jaxbContextDetailed.createUnmarshaller();
			CustomerTestTrans resultCustTrans = (CustomerTestTrans) unmarshaller.unmarshal(inputStream);
			
			//the password isnt set so we need to save it then update the user
			String pw = updateCustBO.getCreateCustTrans().password;
			updateCustBO.setCreateCustTrans(resultCustTrans);
			updateCustBO.getCreateCustTrans().password = pw;
			
		} catch (ParserConfigurationException e) {
			logger.error("ParserConfigurationException " + e.getMessage());
		} catch (JAXBException e) {
			logger.error("JAXBException "  + e.getMessage());
		}
	}
	
	public CustomerTrans GetCustByID(CustomerTestBO createCustBO, int custId, IServerResource server) {

		WebResource resource = server.getResource();

		String custIdString = Integer.toString(custId);
		// make the request (signing it in the process)
		String responce = resource.path("customer").path(custIdString)
				.header("Content-Type", javax.ws.rs.core.MediaType.TEXT_PLAIN)
				.header(DAODefines.SESSIONID_HEADER, createCustBO.getSessionId())
				.accept(javax.ws.rs.core.MediaType.APPLICATION_XML)
				.get(String.class);
		
		//unmashall the return results
		CustomerTrans resultCustTrans = null;
		JAXBContext jaxbContextDetailed;
		try {
			jaxbContextDetailed = JAXBContext.newInstance(CustomerTrans.class);
	
			InputStream inputStream = new ByteArrayInputStream(responce.getBytes());
			Unmarshaller unmarshaller = jaxbContextDetailed.createUnmarshaller();
			resultCustTrans = (CustomerTrans) unmarshaller.unmarshal(inputStream);
		} catch (JAXBException e) {
			logger.error("ParserConfigurationException " + e.getMessage());
		}
		
		return resultCustTrans;
	}
	
	public List<CustomerTrans> GetCustsByPersona(CustomerTestBO createCustBO, String personName, IServerResource server) {

		WebResource resource = server.getResource();

		// make the request (signing it in the process)
		String responce = resource.path("customer").path("group").path(personName)
				.header("Content-Type", javax.ws.rs.core.MediaType.TEXT_PLAIN)
				.header(DAODefines.SESSIONID_HEADER, createCustBO.getSessionId())
				.accept(javax.ws.rs.core.MediaType.APPLICATION_XML)
				.get(String.class);
		
		//unmashall the return results
		CustomerTransList resultCustTrans = null;
		JAXBContext jaxbContextDetailed;
		try {
			jaxbContextDetailed = JAXBContext.newInstance(CustomerTransList.class);
	
			InputStream inputStream = new ByteArrayInputStream(responce.getBytes());
			Unmarshaller unmarshaller = jaxbContextDetailed.createUnmarshaller();
			resultCustTrans = (CustomerTransList) unmarshaller.unmarshal(inputStream);
		} catch (JAXBException e) {
			logger.error("ParserConfigurationException " + e.getMessage());
		}
		
		return resultCustTrans.getList();
	}
}
